package org.sunxin.ch17.filter;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;
import java.util.ResourceBundle;

public class SetLocaleFilter implements Filter
{
    private String resourceName = null;
    
    public void init(FilterConfig filterConfig) throws ServletException
    {
        //获取过滤器的初始化参数，resourceName参数用于指定资源包系列的基名。
        resourceName=filterConfig.getInitParameter("resourceName");
        if(null==resourceName)
        {
            throw new UnavailableException("no define resource");   
        }
    }
    
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
                  throws IOException, ServletException
    {
        HttpServletRequest httpReq=(HttpServletRequest)request;
        HttpServletResponse httpResp=(HttpServletResponse)response;
        
        //返回客户端首选的Locale对象
        Locale locale=request.getLocale();
        //如果locale为null，创建对应于英文的Locale对象
        if(null == locale)
        {
        	locale=new Locale("en");
        }
        
        ResourceBundle bundle=ResourceBundle.getBundle(resourceName,locale);;
        
        HttpSession session=httpReq.getSession();
        
        //将资源包对象设置为Session对象的属性，
        //在其它页面中，可以直接从Session对象中得到资源包。
        session.setAttribute("resource",bundle);
        
        //设置响应正文的编码方式为UTF-8
        httpResp.setCharacterEncoding("UTF-8");
        chain.doFilter(request, response);
    }
   
    public void destroy()
    {
        resourceName=null;
    }
}
